from datetime import datetime, timedelta
from typing import Annotated, Optional

from fastapi import APIRouter, Depends, BackgroundTasks, Request, Body

from sanren.utils import get_current_active_user, Helper
from application.http import models
from application.http.models import OemModel, CodeModel
from application.http.schemas import ApiSchemas
from application.http import schemas
from application.config import appSettings
from sanren.extensions import ExtQiniu


router = APIRouter(prefix='/brand', tags=['Brand'])
module_name = '品牌商模块 - 素材'


@router.get('/assets/created', response_model=schemas.BaseApiListOut)
async def created_tables(
    request: Request,
):
    """
        动态创建表
    """
    OemModel.AssetCategory.create_table()
    OemModel.Asset.create_table()
    OemModel.Download.create_table()
    OemModel.CodeCollection.create_table()

    return {'data': 'ok'}


@router.get('/assets/categories', response_model=schemas.BaseApiListOut)
async def get_asset_categories(
    current_user: Annotated[object, Depends(get_current_active_user)],
    request: Request,
    page_params: schemas.PageParams = Depends(),
    brand_id: Optional[int] = None,
):
    """
        素材分类列表
    """

    objs = OemModel.AssetCategory.with_('brand').with_('children').with_('children.brand').where('parent_id', 0)

    if brand_id:
        objs = objs.where('brand_id', brand_id)

    objs = objs.order_by('id', 'desc').all()

    return {'data': objs.serialize(), 'meta': {'total': len(objs)}}


@router.post('/assets/categories', response_model=schemas.BaseApiOut)
async def add_asset_category(
    current_user: Annotated[object, Depends(get_current_active_user)],
    request: Request,
    post: dict = Body(),
):
    """
        添加素材分类
    """

    try:
        obj = OemModel.AssetCategory()  # 实例化对象
        obj.name = post.get('name', '')
        obj.brand_id = post.get('brand_id', 0)
        obj.brand_code = post.get('brand_code', None)
        obj.parent_id = post.get('parent_id', 0)
        obj.level = post.get('level', 1)
        obj.save()

        return {}
    except Exception as e:
        return {'data': 'error', 'message': f'操作失败:{str(e)}'}


@router.put('/assets/categories/{id}', response_model=schemas.BaseApiOut)
async def edit_asset_category(
    current_user: Annotated[object, Depends(get_current_active_user)],
    request: Request,
    post: dict = Body(),
    id: int = 0,
):
    """
        编辑素材分类
    """

    obj = OemModel.AssetCategory.find(id)
    if obj is None:
        return {'code': 1, 'message': '分类不存在'}

    try:
        # 更新信息
        obj.name = post.get('name', '')
        obj.brand_id = post.get('brand_id', 0)
        obj.brand_code = post.get('brand_code', None)
        obj.save()

        return {}
    except Exception as e:
        return {'code': 1, 'message': f'操作失败:{str(e)}'}


@router.delete('/assets/categories/{id}', response_model=schemas.BaseApiOut)
async def delete_asset_category(
    current_user: Annotated[object, Depends(get_current_active_user)],
    request: Request,
    id: int = 0,
):
    """
        删除素材分类
    """

    obj = OemModel.AssetCategory.find(id)
    if obj is None:
        return {'code': 1, 'message': '分类不存在'}

    if OemModel.Asset.where('category_id', id).count() > 0:
        return {'code': 1, 'message': '该分类下有素材，不能删除'}

    try:
        obj.delete()

        return {}
    except Exception as e:
        return {'code': 1, 'message': f'操作失败:{str(e)}'}


@router.get('/assets', response_model=schemas.BaseApiListOut)
async def get_assets(
    current_user: Annotated[object, Depends(get_current_active_user)],
    request: Request,
    page_params: schemas.PageParams = Depends(),
    brand_id: Optional[int | str] = None,
    category_id: Optional[int | str] = None,
    keyword: Optional[str] = None,
):
    """
        品牌商 素材列表
    """

    objs = OemModel.Asset.with_('brand')

    if brand_id is not None and brand_id != '':
        objs = objs.where('brand_id', brand_id)

    if category_id is not None and category_id != '':
        objs = objs.where('category_id', category_id)

    if keyword:
        objs = objs.where(
            lambda query: query.where(
                'name', 'like', f'%{keyword}%'
            ).or_where(
                'path', 'like', f'%{keyword}%'
            )
        )

    objs = objs.order_by('id', 'desc').paginate(page_params.pageSize, page_params.page)

    return objs.serialize()


@router.post('/assets', response_model=schemas.BaseApiOut)
async def add_asset(
    current_user: Annotated[object, Depends(get_current_active_user)],
    request: Request,
    post: dict = Body(),
):
    """
        添加素材
    """

    try:
        # 更新文件名称信息
        data = {
            'brand_id': post.get('brand_id', 0),
            'brand_code': post.get('brand_code', None),
            'category_id': post.get('category_id', 0),
            'name': post.get('name', ''),
            'url': post.get('url', ''),
            'path': post.get('path', ''),
            'is_public': post.get('is_public', 1),
            'position': post.get('position', 1),
            'type': post.get('type', 1),
            'admin_id': current_user.id,
        }
        OemModel.Asset.create(data)

        return {'message': '操作成功'}
    except Exception as e:
        return {'code': 1, 'message': f'操作失败:{str(e)}'}


@router.put('/assets/{id}', response_model=schemas.BaseApiOut)
async def edit_asset(
    current_user: Annotated[object, Depends(get_current_active_user)],
    request: Request,
    post: dict = Body(),
    id: int = 0,
):
    """
        编辑素材
    """

    obj = OemModel.Asset.find(id)
    if obj is None:
        return {'code': 1, 'message': '此信息不存在'}

    try:
        # 更新文件名称信息
        obj.name = post.get('name', '')
        obj.save()

        return {}
    except Exception as e:
        return {'code': 1, 'message': f'操作失败:{str(e)}'}


@router.delete('/assets/{id}', response_model=schemas.BaseApiOut)
async def delete_asset(
    current_user: Annotated[object, Depends(get_current_active_user)],
    request: Request,
    id: int = 0,
):
    """
        删除素材
    """

    obj = OemModel.Asset.find(id)
    if obj is None:
        return {'code': 1, 'message': '此信息不存在'}

    try:
        # 删除云端图片
        if obj.position == 1:
            qiniu = ExtQiniu()
            qiniu.delete_file(obj.path)

        obj.delete()

        return {}
    except Exception as e:
        return {'code': 1, 'message': f'操作失败:{str(e)}'}
